package com.pc.scrs.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pc.scrs.utils.JwtUtils;
import com.pc.scrs.utils.ResponseResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录成功后的处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    //jackson对象
    private final ObjectMapper mapper=new ObjectMapper();
    /**
     * 登录成功后自动执行的方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得登录用户在security中的对象
        User user= (User) authentication.getPrincipal();
        //设置响应数据的编码格式
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ResponseResult<Object> responseResult=null;
        PrintWriter out=httpServletResponse.getWriter();
        try {
            //调用生成token方法
            String token = JwtUtils.createJwtToken(user.getUsername());
            //将ResponseResult转为json
            out.write(mapper.writeValueAsString(new ResponseResult<>(200, "登录成功",token)));//JackSon中将对象序列化为json字符串的方法
        } catch (Exception e) {
            out.write(mapper.writeValueAsString(new ResponseResult<Object>(6001,"token异常")));
        } finally {
            out.flush();
            out.close();
        }
    }
}
